﻿@using SubstrateHelper.Models;
@using SubstrateHelper.Data;
@using ProcessBase.Models;
@using System.Collections.Concurrent;
@using System.Collections.Generic;
@using System.Linq;
@using System.Timers;
@inject SubstrateHelperDbContext Db
@inject MessageService MessageService


<div>
    <div class="m-1">
        <span>
            <strong class="text-success">主批号 </strong>（包含）：
            <input type="text" @bind="LotNo" style="width:100px">
        </span>
        <span class="ml-3">
            <strong class="text-success">来料标识 </strong>（包含）：
            <input type="text" @bind="InputLotNo" style="width:100px">
        </span>
        <span class="ml-3">
            <strong class="text-success">产出标识 </strong>（包含）：
            <input type="text" @bind="OutputLotNo" style="width:100px">
        </span>

        <span class="ml-3">
            <strong class="text-success">工序 </strong>：
            <select @bind="SelectedProcess">
                <option value="-1">所有类型</option>
                @if (Processes != null)
                {
                    @for (int i = 0; i < Processes.Count; i++)
                    {
                        <option value="@i">@Processes[i]</option>
                    }
                }

            </select>
        </span>

        <span class="ml-3">
            <strong class="text-success">回溯起始批号</strong>（完整）：
            <select @bind="SelectedLotToTraceback">

                @if (LotsToTraceback != null)
                {
                    @foreach (var a in LotsToTraceback)
                    {
                        <option value="@a.Key">@a.Value</option>
                    }
                }

            </select>
        </span>







        <Button class="ml-3" IsOutline="false" Color="Color.Success" @onclick="DoQuery">查  询</Button>
    </div>


    <hr class="bg-primary" style="height:5px;" />
    <ComponentProcessStatistics Items="@Items" />


</div>
<Message />

@code {

    List<string> Processes
    {
        get
        {
            if (_Processes == null)
            {
                try
                {
                    _Processes = Db.Parameters.Select(x => x.ProcessName).Distinct().OrderBy(x => x).ToList();
                }
                catch
                {
                    _Processes = null;
                }
            }
            return _Processes;
        }


    }
    List<string> _Processes = null;

    int SelectedProcess { get; set; } = -1;

    string LotNo { get; set; }
    string OutputLotNo { get; set; }
    string InputLotNo { get; set; }


    List<ProcessBase.Models.ProcessStatistics> Items { get; set; }


    //List<string> LotNosToTraceback { get; set; }
    //int SelectedLotNoToTranceback { get; set; } = -1;

    List<KeyValuePair<string,string>> LotsToTraceback { get; set; }
    string SelectedLotToTraceback
    {
        get
        {
            return _SelectedLotToTraceback;
        }
        set
        {
            _SelectedLotToTraceback = value;
            if (_SelectedLotToTraceback != null)
            {
                _MakeTracebackLinks(_SelectedLotToTraceback);
            }
        }
    }
    string _SelectedLotToTraceback = null;



    private void DoQuery()
    {

        try
        {
            //主批号
            IQueryable<ProcessBase.Models.ProcessStatistics> query = Db.ProcessStatistics;
            if (!string.IsNullOrWhiteSpace(LotNo))
            {
                query = query.Where(x => (x.MainLotNo.Contains(LotNo)));
            }

            IQueryable<string> guids = query.Select(x => x.Guid).Distinct();

            //来料标识
            if (!string.IsNullOrWhiteSpace(InputLotNo))
            {
                query = query.Where(x => (x.LotNoInput.Contains(InputLotNo)));
            }


            //产出标识
            if (!string.IsNullOrWhiteSpace(OutputLotNo))
            {
                query = query.Where(x => (x.LotNoOutput.Contains(OutputLotNo)));
            }

            //工序            
            if (SelectedProcess >= 0)
            {
                query = query.Where(x => (x.ProcessName== Processes[SelectedProcess]));
            }

            //生成guid-lotno词典
            List<KeyValuePair<string, string>> lots = new List<KeyValuePair<string, string>>();
            foreach (var ps in query)
            {
                lots.Add(new KeyValuePair<string, string>(ps.Guid, $"{ps.LotNoOutput} @ <{ps.ProcessName}>"));
            }
            LotsToTraceback = lots.OrderBy(x => x.Value).ToList();



            if (LotsToTraceback.Count>1)
            {
                //MessageService?.Show(new MessageOption()
                //{
                //    Content = $"警告：有多个起始批号满足查询条件。默认按第1个回溯批号查询。请按需要选择回溯批号！",
                //    Icon = "fa fa-info-circle",
                //    ShowDismiss = true,
                //    Color = Color.Warning
                //});
            }
            else if(LotsToTraceback.Count <=0)
            {
                MessageService?.Show(new MessageOption()
                {
                    Content = $"返回0条结果。",
                    Icon = "fa fa-info-circle",
                    ShowDismiss = true,
                    Color = Color.Success
                });
                return;
            }

            SelectedLotToTraceback = LotsToTraceback[0].Key; //选定第一个







        }
        catch (Exception ex)
        {
            MessageService?.Show(new MessageOption()
            {
                Content = $"发生错误：{ex.Message}",
                Icon = "fa fa-info-circle",
                ShowDismiss = true,
                Color = Color.Danger
            });
        }









    }


    private void _MakeTracebackLinks(string guid)
    {
        try
        {
            Items = Helpers.ProcessTraceHelper.GetTracingLinks(guid);
            if (Items == null)
            {
                MessageService?.Show(new MessageOption()
                {
                    Content = $"返回0条结果。",
                    Icon = "fa fa-info-circle",
                    ShowDismiss = true,
                    Color = Color.Success
                });
            }
            else
            {
                MessageService?.Show(new MessageOption()
                {
                    Content = $"返回{Items.Count}条结果。",
                    Icon = "fa fa-info-circle",
                    ShowDismiss = true,
                    Color = Color.Success
                });
            }

        }
        catch(Exception ex)
        {
            MessageService?.Show(new MessageOption()
            {
                Content = $"发生错误：{ex.Message}",
                Icon = "fa fa-info-circle",
                ShowDismiss = true,
                Color = Color.Danger
            });
        }


    }





}
